package com.liveforstudy.common.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author angel.bin@aliyun.com
 * @since 2020-10-05 10:23
 */
public class JsonUtils {
    /**
     * 序列化配置
     */
    private static final SerializeConfig SERIALIZE_CONFIG;
    /**
     * 输出配置
     */
    private static final SerializerFeature[] SERIALIZER_FEATURES;

    static {
        SERIALIZE_CONFIG = new SerializeConfig();
        // 使用和json-lib兼容的日期输出格式
        SERIALIZE_CONFIG.put(java.util.Date.class, new JSONLibDataFormatSerializer());
        SERIALIZE_CONFIG.put(java.sql.Date.class, new JSONLibDataFormatSerializer());
        SERIALIZE_CONFIG.put(java.time.LocalDate.class, new JSONLibDataFormatSerializer());
        SERIALIZE_CONFIG.put(java.time.LocalTime.class, new JSONLibDataFormatSerializer());
        SERIALIZE_CONFIG.put(java.time.Year.class, new JSONLibDataFormatSerializer());
        SERIALIZE_CONFIG.put(java.time.YearMonth.class, new JSONLibDataFormatSerializer());
        SERIALIZE_CONFIG.put(java.time.LocalDateTime.class, new JSONLibDataFormatSerializer());
        SERIALIZE_CONFIG.put(java.time.Instant.class, new JSONLibDataFormatSerializer());
        //配置输出格式
        SERIALIZER_FEATURES = new SerializerFeature[]{
                // 输出空置字段
                SerializerFeature.WriteMapNullValue,
                // list字段如果为null，输出为[]，而不是null
                SerializerFeature.WriteNullListAsEmpty,
                // 数值字段如果为null，输出为0，而不是null
                SerializerFeature.WriteNullNumberAsZero,
                // Boolean字段如果为null，输出为false，而不是null
                SerializerFeature.WriteNullBooleanAsFalse,
                // 字符类型字段如果为null，输出为""，而不是null
                SerializerFeature.WriteNullStringAsEmpty,
                //禁止循环引用检测
                SerializerFeature.DisableCircularReferenceDetect
        };
    }

    private JsonUtils() {
    }

    public static String toJson(Object obj) {
        return JSON.toJSONString(obj, SERIALIZE_CONFIG, SERIALIZER_FEATURES);
    }

    public static Object toBean(String json) {
        return JSON.parse(json);
    }

    public static <T> T toBean(String json, Class<T> clazz) {
        return JSON.parseObject(json, clazz);
    }

    public static <T> List<T> toArray(String json, Class<T> clazz) {
        return JSON.parseArray(json, clazz);
    }
}
